import { User } from '@@/server/models/User';

export default defineEventHandler(async (event) => {
	if (event.method !== 'POST') {
		throw createError({
			statusCode: 405,
			message: '方法不允许',
		});
	}
	try {
		const { email, password } = await readBody(event);
		// 验证必填字段
		if (!email || !password) {
			throw createError({
				statusCode: 400,
				message: '邮箱和密码都是必填项',
			});
		}
		// 查找用户
		const user = await User.findOne({ email });
		if (!user) {
			throw createError({
				statusCode: 401,
				message: '用户不存在',
			});
		}
		// 验证密码
		const isMatch = await user.comparePassword(password);
		if (!isMatch) {
			throw createError({
				statusCode: 401,
				message: '密码错误',
			});
		}
		// 返回用户信息（不包含密码）
		return {
			message: '登录成功',
			user: {
				id: user._id,
				username: user.username,
				email: user.email,
			},
		};
	} catch (error: any) {
		throw createError({
			statusCode: error.statusCode || 500,
			message: error.message || '登录失败',
		});
	}
}); 